package ledger

import (
	"bgs/conf"
	"bgs/grpc/imp/enums"
	"bgs/nsqp/topic"
	"bgs/nsqp/util"
	"bgs/service/model"
	"encoding/json"

	"github.com/nsqio/go-nsq"
	"go.uber.org/zap"
)

// NsqLedgerRunner publish nsq message producer
type NsqLedgerRunner struct {
	slog     *zap.SugaredLogger
	producer *nsq.Producer
}

// NewNsqLedgerRunner initialization
func NewNsqLedgerRunner(
	nsqConf conf.NsqSection,
	slog *zap.SugaredLogger,
) (proxy *NsqLedgerRunner, err error) {
	proxy = &NsqLedgerRunner{
		slog: slog.With("module", "NsqLedgerRunner"),
	}
	config := nsq.NewConfig()

	producer, err := nsq.NewProducer(nsqConf.NsqdAddress, config)
	if err != nil {
		return
	}
	proxy.producer = producer
	nsqLogger := util.NewNoopNSQLogger(slog)
	producer.SetLogger(
		nsqLogger,
		nsq.LogLevelError,
	)

	// Gracefully stop the consumer.
	// consumer.Stop()

	return
}

// PublishAddProfitReceiver 发送添加分账者消息
func (s *NsqLedgerRunner) PublishAddProfitReceiver(ptr *model.ProfitReceiver) (err error) {
	body, err := json.Marshal(ptr)
	if err != nil {
		return
	}
	err = s.producer.Publish(util.MakeTopic(enums.APPIDBGS)(topic.AddProfitReceiver), body)
	return
}
